<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Session;
use DB;
class orderController extends Controller
{
    public function index()
    {
    	return view('home.order.order');
    }
    public function insert(Request $request)
    { 
    	$cnt = DB::table('cart')
        ->select(DB::raw('count(cid) as cnt'))
        ->first();
      $res = DB::table('cart')
        ->leftJoin('goods','goods.gid','=','cart.gid')
        ->where('uid',session('homeM')->uid)
        ->get();
      $sum = 0;
        foreach($res as $k => $v)
        {
            $sum += $v -> price * $v -> count;
        }

      $time = time();
      $rand = rand(1000,9999);
      $data = $request -> except('_token');
      $data['oid'] = $time.$rand;
      $data['uid'] = session('homeM')->uid;
      $data['otime'] = Date('Y-m-d H:i:s');
      $data['ocnt'] = $cnt->cnt;
      $data['ormb'] = $sum;
      Session::put('oid',$data['oid']);
      $res = DB::table('order')->insert($data);
      if ($res) 
      {

      	return redirect('/home/order/jsy');
      }else
      {
      	return back()->with(['info'=>'失败']);
      }

    }
    public function jsy()
    {
      $data = DB::table('order')
      ->where('oid',session('oid'))->first();
      $uid = $data -> uid;
      $goods = DB::table('cart')
      ->leftJoin('goods','cart.gid','=','goods.gid')
      ->where('cart.uid',$uid)
      ->get();
      $sum = 0;
      $num = 0;
      foreach($goods as $k => $v)
      {
        $sum += $v -> price * $v -> count;
        $num += $v ->count;

      }
      return view('home.order.jsy',['data'=>$data,'goods'=>$goods,'sum'=>$sum,'num'=>$num]);
    }
    public function ok(Request $request)
    {
      $oid = session('oid');
      $detail['oid']=$oid;
      $data = DB::table('cart') -> where('uid',Session('homeM')->uid) -> get();
      foreach($data as $row)
        {
          // 拼detail表数据
          $res = DB::table('goods') -> where('gid',$row -> gid) -> first();
          $row -> gid = $res;
          $detail['gid'] = $row ->gid -> gid;
          $detail['buyprice'] = $row -> gid -> price;
          $detail['buycnt'] = $row -> count;
    
          $aa = DB::table('detail') -> insert($detail);
          if(!$aa)
          {
            DB::rollback();
            return back();
          }
        }
      $vid = DB::table('order')->where('oid',$detail['oid'])->first();
      DB::table('cart')->where('uid',session('homeM')->uid)->delete();
      return view('home.order.jsy_ok',['vid'=>$vid]);
    }

}
